<template>
	<div style="display: inline-block">
		<a-upload
			v-model:file-list="fileList"
			:list-type="listType"
			:class="listType === 'text' ? '' : 'avatar-uploader'"
			:show-upload-list="false"
			:before-upload="beforeUpload"
			:custom-request="customRequest"
			:max-count="1"
			accept="image/jpg, image/jpeg, image/png, image/gif"
		>
			<template v-if="listType === 'text'">
				<a-button type="link">上传</a-button>
			</template>
			<template v-else>
				<img v-if="imageUrl" :src="imageUrl" alt="图片" class="avatar-img" />
				<div v-else>
					<loading-outlined :style="{ fontSize: '26px', color: '#666' }" v-if="loading"></loading-outlined>
					<picture-outlined :style="{ fontSize: '26px', color: '#666' }" v-else></picture-outlined>
					<div style="margin-top: 8px; color: #666">上传</div>
				</div>
			</template>
		</a-upload>
	</div>
</template>
<script setup>
	import { message } from 'ant-design-vue'
	import fileApi from '@/api/dev/fileApi'
	//                                  logo            状态
	const emit = defineEmits(['update:modelValue', 'resetFormStatus'])
	const props = defineProps({
		modelValue: {
			type: String,
			default: ''
		},
		// 限制文件大小，单位M
		fileSize: {
			type: Number,
			default: 2
		},
		// 上传按钮样式 text, picture 和 picture-card
		listType: {
			type: String,
			default: 'picture-card'
		}
		// 唯一标识符，不设置时会自动生成
		// uid: {
		//     type: String,
		//     default: '-1'
		// }
	})
	//computed确保有默认值
	const imageUrl = computed({
		//读
		get() {
			return props.modelValue || ''
		},
		//写
		set(val) {
			emit('update:modelValue', val)
		}
	})

	const fileList = ref([])
	const loading = ref(false)

	/**
	 * 限制上传文件的格式和大小
	 */
	const beforeUpload = (file) => {
		const isJpgOrPng =
			file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
		if (!isJpgOrPng) {
			message.error('只能上传JPG、JPEG、PNG、GIF格式的图片~')
		}
		const isLtM = file.size / 1024 / 1024 < props.fileSize
		if (!isLtM) {
			message.error(`文件超过${props.fileSize}M限制，不允许上传~`)
		}
		return isJpgOrPng && isLtM
		//return isLtM
	}

	/**
	 * 自定义上传实现
	 */
	const customRequest = async (options) => {
		loading.value = true
		//这一步起到的作用是什么
		const { file } = options
		const formData = new FormData()
		formData.append('file', file)
		await fileApi
			.fileUploadAliyunReturnUrl(formData)
			.then((res) => {
				loading.value = false
				imageUrl.value = res
				emit('resetFormStatus')
			})
			.finally(() => {
				loading.value = false
			})
	}
</script>
<style scoped>
	.ant-upload-picture-card-wrapper {
		width: auto;
	}
	.avatar-img {
		max-width: 100%;
		max-height: 100%;
	}
</style>
